#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <vector>

using namespace std;

class QueryText{
public:
    void read(const string & filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "file is not found" << endl;
            return;
        }

        string line;
        int lineNum = 0;
        while(getline(ifs,line)){
            _lines.push_back(line);

            ++lineNum;
            istringstream iss(line);
            string word;
            while(iss >> word){
                _wordNumbers[word].insert(lineNum);
                ++_wordTimes[word];
            }
        }
    }

    void query(const string & word){
        cout << word << " occurs " << _wordTimes[word] << " times." << endl;
        cout << "-----------------------------------" << endl;
        auto it = _wordNumbers.find(word);
        if(it != _wordNumbers.end()){
            for(auto & linenum : it->second){
                cout << "(line" << linenum << ")";
                cout << _lines[linenum -1] << endl;
            }
        }else{
            cout << word << " is not exist " << endl;
        }
        cout << "----------------------------------" << endl;
    }
private:
    vector<string> _lines;
    map<string,set<int>> _wordNumbers;
    map<string,int> _wordTimes;
};

void test(){
    string queryWord("the");
    
    QueryText qt;
    qt.read("china_daily.txt");
    qt.query(queryWord);
}

int main()
{
    test();
    return 0;
}

